<?php

namespace addons\shopro\job;

use addons\shopro\library\traits\ActivityCache;
use addons\shopro\library\traits\Groupon;
use addons\shopro\library\traits\StockSale;
use addons\shopro\model\Config;
use addons\shopro\model\GoodsComment;
use addons\shopro\model\Order;
use addons\shopro\model\OrderAction;
use addons\shopro\model\OrderItem;
use app\admin\model\Admin;
use think\Db;
use think\queue\Job;

/**
 * 订单支付完成
 */
class OrderPayed extends BaseJob
{
    use StockSale, ActivityCache, Groupon;

    /**
     * 订单支付完成
     */
    public function payed(Job $job, $data)
    {
        try {
            $order = $data['order'];
            $user = $data['user'];

            $order = Order::with('item')->where('id', $order['id'])->find();

            // 数据库删订单的问题常见，这里被删的订单直接把队列移除
            if ($order) {
                \think\Db::transaction(function () use ($order, $user, $data) {
                    // 订单减库存
                    $this->realForwardStockSale($order);

                    // 判断，如果是拼团 真实加入团
                    if (strpos($order['activity_type'], 'groupon') !== false) {
                        $this->joinGroupon($order, $user);
                        $this->joinGrouponIdentity($order, $user);
                    }else{
                         //新拼团
                        //判断有没有团id
                        // 扩展字段
                        $order_ext = $order['ext_arr'];
                        // 团 id
                        $groupon_id = $order_ext['groupon_id'] ?? 0;
                        if (!empty($groupon_id)){
                            $this->joinGrouponNew($order, $user);
                        }

                    }

                    // 处理发票审核
                    if ($order->invoice_status == 1) {
                        $invoice = \addons\shopro\model\OrderInvoice::get(['order_id' => $order->id]);
                        if ($invoice) {
                            $invoice->status = 0;
                            $invoice->save();
                        }
                    }

                    // 处理消费返积分 TODO: 待测试
                    /*$scoreConfig = Config::where('name', 'score')->find();
                    $scoreConfig = json_decode($scoreConfig['value'], true);
                    if(!empty($scoreConfig['consume_get_score']) && !empty($scoreConfig['consume_get_score_ratio'])) {
                        $scoreRatio = intval($scoreConfig['consume_get_score_ratio']);
                        $score = intval($scoreRatio * 0.01 * $order->total_fee);
                        if($score > 0) {
                            \addons\shopro\model\User::score($score, $user['id'], 'consume_get_score', $order['id']);
                        }
                    }*/

                    //赠送积分
                    if ($order->individual_bonus_points_total > 0){
                        \addons\shopro\model\User::score($order->individual_bonus_points_total, $user['id'], 'consume_get_score', $order->id,'',[
                            'order_id' => $order->id,
                            'order_sn' => $order->order_sn,
                        ]);
                    }
                    
                    // 触发订单支付完成事件, 如果这个订单刚好完成拼团，并且是自动发货订单，则这个订单的自动发货事件会比订单支付之后事件早
                    $data = ['order' => $order];
                    \think\Hook::listen('order_payed_after', $data);

                    // 检测有没有自动发货的商品，有就自动发货
                    $order->checkDispatchAndSend($order, ['user' => $user]);
                });


                //开始-2022-2-10 Ripple 自动备货
                $order = Order::where('id', $order->id)->find();
                if ($order) {
                    // 查询要发货的商品
                    $where = [
                        'order_id' => $order->id,
                        'dispatch_type' => 'selfetch',//自提
                        'dispatch_status' => ['in', [\app\admin\model\shopro\order\OrderItem::DISPATCH_STATUS_NOSEND]],
                    ];

                    $itemList = \app\admin\model\shopro\order\OrderItem::where($where)->select();

                    if ($itemList) {
                        // 对选择的 item 进行发货
                        Db::transaction(function () use ($order, $itemList) {
                            $order->adminStoreOrderSend($order, $itemList, ['oper_type' => 'admin', 'oper' => Admin::get(1)]);
                        });
                    }
                }
                //开始-2022-2-10 Ripple 自动备货

                //开始-2022-2-10 Ripple 推送消息
                if ($order->platform_source == '2' || $order->platform_source == '3'){//抖音发送短信 或 快手发送短信
                    if ($user['mobile']){
                        foreach ($order['item'] as $order_item){
                            $msg_data = [
                                'goods_name' => $order_item['goods_title'],
                                'code' => ($order_item['dispatch_type'] == 'express') ? '无':'待商家备货后可查看',
                            ];
                            douyin_sms_buy($user['mobile'],$msg_data);
                        }
                    }
                }else{//微信发送公众号模板消息
                    //判断是不是参与拼团
                    $ext_array = json_decode($order->ext,'true');
                    if (isset($ext_array['groupon_id']) && !empty($ext_array['groupon_id'])){
                        after_successful_payment($order->user_id,$ext_array['groupon_id']);
                        //判断是不是团长 是团长就不发了
                        $groupon_user_id = Db::name('shopro_activity_groupon_log')->where(['groupon_id'=>$ext_array['groupon_id'],'is_leader'=>1])->value('user_id');
                        if ($groupon_user_id != $order->user_id){
                            notify_the_head_of_the_new_order_to_receive($ext_array['groupon_id']);
                        }

                    }
                }
                //结束-2022-2-10 Ripple 推送消息
            }

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
            // 队列执行失败
            $error = json_encode([
                'a' => $e->getLine(),
                'b' => $e->getFile(),
                'c' => $e->getTrace(),
                'd' => $e->getMessage()
            ], JSON_UNESCAPED_UNICODE);


            \think\Log::error('queue-' . get_class() . '-payed' . '：执行失败，错误信息：' . $error);
        }
    }
}
